package com.playtime.layouts.example1;

import javafx.beans.DefaultProperty;
import javafx.collections.ListChangeListener;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.util.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DefaultProperty("children")
public class CustomHBoxBuilder implements Builder<HBox> {

    private static final Logger log = LoggerFactory.getLogger(CustomHBoxBuilder.class);

    private int spacing;
    private List<Node> children = new ArrayList<Node>();
    private List<Constraints> constraints = new ArrayList<Constraints>();

    public List<Node> getChildren() {
        return children;
    }

    public List<Constraints> getConstraints() {
        return constraints;
    }

    public int getSpacing() {
        return spacing;
    }

    public void setSpacing(int spacing) {
        this.spacing = spacing;
    }

    @Override
    public HBox build() {
        HBox hbox = new HBox();
        hbox.setSpacing(spacing);
        if (children != null) {

            if (constraints != null) {
                final Map<String, Constraints> constraintsMap = new HashMap<String, Constraints>();
                for (Constraints constraint : constraints) {
                    constraintsMap.put(constraint.getForNode(), constraint);
                }
                hbox.getChildren().addListener(new ListChangeListener<Node>() {
                    @Override
                    public void onChanged(Change<? extends Node> change) {
                        while (change.next()) {
                            if (change.wasAdded()) {
                                for (Node node : change.getAddedSubList()) {
                                    if (node.getId() != null) {
                                        Constraints newConstraints = constraintsMap.get(node.getId());
                                        if (newConstraints != null) {
                                            log.debug("Applying constraints to node: {}", node.getId());
                                            newConstraints.apply(node);
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }

            hbox.getChildren().setAll(children);
        }
        return hbox;
    }
}
